<template>
  <div>

    <Modal v-model="polygonMapModal" title="小区边界选取" fullscreen  @on-ok="polygonMapModalConfirm">
      <Card class="cardStrleClass">
        <template>
          <Input v-model="inputSearch" placeholder="请输入小区名称" style="width: 200px;margin-right: 20px"/>
        </template>
        <Button type="primary"  @click="autoInput">搜索</Button>
        <Button type="primary"  @click="clearMapPath" style="margin-left: 20px">重新绘制</Button>
        <div style="max-height: 300px;max-width: 320px;overflow-x: auto;overflow-y: auto">
          <span style="font-size: 10px">注：根据输入小区名称获取小区详细地址</span>
          <RadioGroup v-if="dataList.length > 0" v-model="addressResult">
            <Divider />
            <Radio v-for="(item,index) in dataList" :key="index" :label="item.name + item.address">
              <span>{{item.district}} _ {{item.name}}  _ {{item.address}}</span>
            </Radio>
          </RadioGroup>
        </div>
      </Card>
      <div id="mapPolygonForResidential" v-show="mapType === 'GD'"></div>
      <div id="leafletMap" v-show="mapType === 'HT'"></div>
    </Modal>
  </div>
  </template>

<script>

import { autoCenter, autoCenterHT, autoPolygon, getCenter } from '../../../../libs/util'
import { findResidentialForCommunityList, newfindAreaList } from '../../../../api/z-new-grid'
import { mapHTUrl, mapTypeChange } from '../../../../libs/mapTypeUtil'
import * as turf from '@turf/turf'

export default {
  name: 'mapPolygonForResidential',
  data () {
    return {
      mapType: '',
      leafletMap: null,
      csc_mapjson_ht: null,
      cscMapjsonHt: '',
      polygonMapModal: false,
      map: null,
      inputSearch: '',
      addressResult: '',
      dataList: [],
      returnObject: {},
      operationType: '',
      residentialList: [],
      polygons: [],
      updatePolygins: [],
      updatePolygins_ht: [],
      updateResidentialInfo: {},
      url: mapHTUrl(),
      htPolygons: [],
      areaMapInfo: []
    }
  },
  mounted () {
    if (this.$route.query.mapType === 'HT') {
      this.mapType = 'HT'
    } else {
      this.mapType = mapTypeChange()
    }
  },
  methods: {
    // 宏图地图坐标充值
    clearMapPath () {
      let ht = autoCenterHT(this.updatePolygins_ht)
      let arr = [[ht[0], ht[1]], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1])], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1]) + 0.002], [parseFloat(ht[0]), parseFloat(ht[1]) + 0.002]]
      this.updatePolygins_ht = JSON.stringify(arr)
      this.initHTmap()
    },
    // 宏图地图创建
    async initHTmap () {
      if (this.operationType === 'create') {
        await this.findGridResidentialList('')
        await this.findAreaPolygon()
        setTimeout(() => {
          this.LoadingHTMap()
        }, 1000)
      }
      if (this.operationType === 'update') {
        await this.findGridResidentialList(this.updateResidentialInfo.id)
        await this.findAreaPolygon()
        setTimeout(() => {
          this.LoadingHTMap()
        }, 1000)
      }
    },
    // 宏图地图加载
    LoadingHTMap () {
      try {
        var url = this.url
        // eslint-disable-next-line eqeqeq
        if (this.leafletMap !== undefined && this.leafletMap !== null) {
          this.leafletMap && this.leafletMap.remove()
        }
        this.leafletMap = L.map('leafletMap', {
          crs: L.CRS.EPSG4326,
          center: [this.operationType === 'create' ? this.cscMapjsonHt[0] : JSON.parse(this.updatePolygins_ht)[0][0], this.operationType === 'create' ? this.cscMapjsonHt[1] : JSON.parse(this.updatePolygins_ht)[0][1]],
          zoom: 15,
          minZoom: 9,
          trackResize: true
        })
        L.supermap.tiledMapLayer(url).addTo(this.leafletMap)

        // 捕捉绘制控件参数设置
        var options = {
          position: 'topright',
          drawMarker: false, // 添加标点
          drawCircleMarker: false, // 添加圆形标点
          drawCircle: false, // 绘制圆形区域
          drawRectangle: false, // 添加按钮绘制矩形
          drawPolyline: false, // 绘制折线
          drawPolygon: false, // 绘制多边形区域
          drawSingleline: false, // 绘制线段
          editPolygon: false, // 编辑图层区域
          deleteLayer: false, // 删除图层
          cutPolygon: false, // 添加一个按钮以删除多边形里面的部分内容
          drawText: false,
          editControls: false
        }
        // 添加捕捉绘制控件
        this.leafletMap.pm.addControls(options)

        // 不可编辑
        let nearbyArr = []
        let arr = []
        nearbyArr = this.residentialList.map((i) => {
          let p = []
          if (this.updatePolygins_ht !== i.csc_mapjson_ht) {
            JSON.parse(i.csc_mapjson_ht || '[[0,0]]').forEach(d => {
              p.push([d[0], d[1]])
              // L.marker([d[0], d[1]], {}).addTo(this.leafletMap)
            })
          }
          return p
        })
        nearbyArr.forEach(i => {
          L.polygon([i], { color: '#cb62f7', weight: 2, fillColor: '#dac0e6', fillOpacity: 0.3 }).addTo(this.leafletMap)
        })
        // L.polygon(JSON.parse(this.areaMapInfo.company_scope_ht), { color: '#000000', weight: 2, fillColor: '#dac0e6', fillOpacity: 0.3 }).addTo(this.leafletMap)
        // 可编辑
        let d = JSON.parse(this.updatePolygins_ht)
        d.forEach((i) => {
          arr.push([i[0], i[1]])
        })
        this.htPolygons = L.polygon(arr, { weight: 2, fillOpacity: 0.3 }).addTo(this.leafletMap)
        this.htPolygons.pm.enable({
          allowSelfIntersection: false
        })
        // 处理点开地图，不进行拖动
        let arrCreate = []
        this.htPolygons.getLatLngs()[0].forEach(i => {
          arrCreate.push([i.lat, i.lng])
        })
        this.csc_mapjson_ht = JSON.stringify(arrCreate)
        // 拖动事件
        this.htPolygons.on('pm:edit', e => {
          let newpath = []
          e.layer.toGeoJSON().geometry.coordinates[0].forEach(item => {
            newpath.push([item[1], item[0]])
          })
          this.csc_mapjson_ht = JSON.stringify(newpath)
        })
      } catch (err) {
        console.log(err)
      }
    },
    // 新增
    init (e) {
      // 宏图地图初始化
      if (this.mapType === 'HT') {
        if (e.csc_mapjson_ht === undefined || e.csc_mapjson_ht === '' || !e.csc_mapjson_ht) {
          this.$Notice.error({ title: '社区中心点异常！', desc: '社区中心点为空，请先选择社区中心点！' })
          return
        }
        let ht = e.csc_mapjson_ht.split(',')
        let arr = [[ht[0], ht[1]], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1])], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1]) + 0.002], [parseFloat(ht[0]), parseFloat(ht[1]) + 0.002]]
        this.updatePolygins_ht = JSON.stringify(arr)
        this.cscMapjsonHt = e.csc_mapjson_ht.split(',')
        this.operationType = 'create'
        this.polygonMapModal = true
        this.initHTmap()
      }
      // 高德地图初始化
      if (this.mapType === 'GD') {
        if (e.csc_mapjson === undefined || e.csc_mapjson === '' || !e.csc_mapjson) {
          this.$Notice.error({ title: '社区中心点异常！', desc: '社区中心点为空，请先选择社区中心点！' })
          return
        }
        this.operationType = 'create'
        this.polygonMapModal = true
        let _this = this
        setTimeout(function () {
          _this.initMap(getCenter(e, _this))
        }, 1000)
      }
    },
    // 修改
    updateInit (e, communityList, cscMapjsonHt) {
      this.updateResidentialInfo = e
      // 宏图地图修改
      if (this.mapType === 'HT') {
        this.cscMapjsonHt = cscMapjsonHt.split(',')
        if (e.csc_mapjson_ht === undefined) {
          let ht = cscMapjsonHt.split(',')
          let arr = [[parseFloat(ht[0]), parseFloat(ht[1])], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1])], [parseFloat(ht[0]) + 0.003, parseFloat(ht[1]) + 0.002], [parseFloat(ht[0]), parseFloat(ht[1]) + 0.002]]
          this.updatePolygins_ht = JSON.stringify(arr)
        } else {
          this.updatePolygins_ht = e.csc_mapjson_ht || '[[0,0]]'
        }
        this.operationType = 'update'
        this.polygonMapModal = true
        this.initHTmap()
      }
      // 高德地图修改
      if (this.mapType === 'GD') {
        this.updatePolygins = e.csc_mapjson
        let x = autoCenter(this.updatePolygins)
        this.operationType = 'update'
        this.polygonMapModal = true
        let _this = this
        setTimeout(function () {
          _this.initMap(x)
        }, 1000)
      }
    },
    // 高德创建地图
    initMap (e) {
      this.map = new AMap.Map('mapPolygonForResidential', {
        resizeEnable: true,
        center: new AMap.LngLat(e.lng, e.lat),
        zoom: 16
      })
      if (this.operationType === 'create') {
        this.polygons = autoPolygon(e)
        this.createPolygon()
        this.findGridResidentialList('')
      }
      if (this.operationType === 'update') {
        this.updatePolygon()
        this.findGridResidentialList(this.updateResidentialInfo.id)
      }
      this.createMaker(e)
    },
    createPolygon () {
      var path = []
      let data = this.polygons
      data.forEach(item => {
        path.push(new AMap.LngLat(item[0], item[1]))
      })
      var Polygon = new AMap.Polygon({
        path: path,
        strokeColor: '#1E9FFF',
        strokeWeight: 2,
        strokeStyle: 'solid',
        strokeOpacity: 1,
        fillOpacity: 0.1,
        fillColor: '#1E9FFF',
        zIndex: 50
      })
      Polygon.on('mouseover', function (e) {
        Polygon.setOptions({
          fillColor: '#FFB800'
        })
      })
      Polygon.on('mouseout', function (e) {
        Polygon.setOptions({
          fillColor: '#1E9FFF'
        })
      })
      this.Polygon = Polygon
      var polyEditor = new AMap.PolyEditor(this.map, this.Polygon)
      polyEditor.open()
      this.map.setFitView([ Polygon ])
      this.map.setZoom(this.map.getZoom() - 2)
      this.map.add(Polygon)
    },
    updatePolygon () {
      var path = []
      let data = JSON.parse(this.updatePolygins)
      data.forEach(item => {
        path.push(new AMap.LngLat(item[0], item[1]))
      })
      var Polygon = new AMap.Polygon({
        path: path,
        strokeColor: '#1E9FFF',
        strokeWeight: 2,
        strokeStyle: 'solid',
        strokeOpacity: 1,
        fillOpacity: 0.1,
        fillColor: '#1E9FFF',
        zIndex: 50
      })
      Polygon.on('mouseover', function (e) {
        Polygon.setOptions({
          fillColor: '#FFB800'
        })
      })
      Polygon.on('mouseout', function (e) {
        Polygon.setOptions({
          fillColor: '#1E9FFF'
        })
      })
      this.Polygon = Polygon
      var polyEditor = new AMap.PolyEditor(this.map, this.Polygon)
      polyEditor.open()
      this.map.setFitView([ Polygon ])
      this.map.setZoom(this.map.getZoom() - 1)
      this.map.add(Polygon)
    },
    createMaker (e) {
      this.marker = new AMap.Marker({
        position: new AMap.LngLat(e.lng, e.lat)
      })
      this.map.add(this.marker)
    },
    autoInput () {
      if (!this.inputSearch) return
      let _this = this
      var keywords = _this.inputSearch
      var autoOptions = {
        city: '沈阳'
      }
      var autoComplete = new AMap.Autocomplete(autoOptions)
      autoComplete.search(keywords, function (status, result) {
        _this.dataList = result.tips
      })
    },
    polygonMapModalConfirm () {
      this.returnObject.polygonResult = {}
      if (this.mapType === 'GD') {
        for (var i = 0; i < this.residentialList.length; i++) {
          var path = []
          let data = JSON.parse(this.residentialList[i].csc_mapjson)
          data.forEach(item1 => {
            path.push(new AMap.LngLat(item1[0], item1[1]))
          })
          var Polygon = new AMap.Polygon({
            path: path,
            strokeColor: '#1E9FFF',
            strokeWeight: 2,
            strokeStyle: 'solid',
            strokeOpacity: 1,
            fillOpacity: 0.1,
            fillColor: '#1E9FFF',
            zIndex: 50,
            extData: {
              name: this.residentialList[i].name
            }
          })
          let result = AMap.GeometryUtil.doesRingRingIntersect(this.Polygon.getPath(), Polygon.getPath())
          if (result) {
            console.log('绘制失败！')
            this.$Notice.error({ title: '绘制失败！', desc: Polygon.getExtData().name + '与当前小区范围重合-1' })
            this.returnObject.polygonResult = {
              name: Polygon.getExtData().name
            }
          }
        }
        this.polygons = this.Polygon.getPath()
        let newpath = []
        this.polygons.forEach(item => {
          let lng = item.lng
          let lat = item.lat
          let point = [lng, lat]
          newpath.push(point)
        })
        var resultPolyons = JSON.stringify(newpath)
      }
      if (this.operationType === 'create') {
        this.returnObject.name = this.inputSearch
        this.returnObject.address = this.addressResult
        if (this.mapType === 'GD') {
          this.returnObject.csc_mapjson = resultPolyons
          this.returnObject.measure = this.Polygon.getArea()
        }
        if (this.mapType === 'HT') {
          this.returnObject.csc_mapjson_ht = this.csc_mapjson_ht
          this.returnObject.measure = turf.area(this.htPolygons.toGeoJSON())
        }
        this.returnObject.operationType = 'create'
      }
      if (this.operationType === 'update') {
        if (this.mapType === 'GD') {
          this.returnObject.csc_mapjson = resultPolyons
          this.returnObject.measure = this.Polygon.getArea()
        }
        if (this.mapType === 'HT') {
          this.returnObject.csc_mapjson_ht = this.csc_mapjson_ht
          this.returnObject.measure = turf.area(this.htPolygons.toGeoJSON())
        }
        this.returnObject.operationType = 'update'
      }
      this.returnObject.mapType = this.mapType
      this.$emit('returnMapInfoForResidential', this.returnObject)
    },
    findGridResidentialList (e) {
      let data = {
        id: e
      }
      findResidentialForCommunityList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.residentialList = ret.data.data
          if (this.mapType === 'GD') {
            this.residentialList.forEach(item => {
              if (item.csc_mapjson) {
                try {
                  this.findCommunityResidentiallygon(JSON.parse(item.csc_mapjson))
                } catch (e) {
                  console.log(e)
                }
              }
            })
          }
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
    },
    findCommunityResidentiallygon (e) {
      var path = []
      let data = e
      data.forEach(item => {
        path.push(new AMap.LngLat(item[0], item[1]))
      })
      var Polygon = new AMap.Polygon({
        path: path,
        strokeColor: '#E066FF',
        strokeWeight: 2,
        strokeStyle: 'solid',
        strokeOpacity: 1,
        fillOpacity: 0.1,
        fillColor: '#E066FF',
        zIndex: 50
      })
      Polygon.on('mouseover', function (e) {
        Polygon.setOptions({
          fillColor: '#EEDC82'
        })
      })
      Polygon.on('mouseout', function (e) {
        Polygon.setOptions({
          fillColor: '#E066FF'
        })
      })
      this.map.add(Polygon)
    },
    findAreaPolygon () {
      let severUserInfo = this.$store.state.user.severUserInfo
      newfindAreaList().then(ret => {
        if (ret.data.errcode === 0) {
          let data = ret.data.data
          if (severUserInfo.company_grade === '3') {
            data.forEach(item => {
              if (item.id === severUserInfo.company_id) {
                this.areaMapInfo = item
              }
            })
            // severUserInfo.company_id
          }
          if (severUserInfo.company_grade === '4') {
            data.forEach(item => {
              if (item.id === severUserInfo.parent_id) {
                this.areaMapInfo = item
              }
            })
            // severUserInfo.parent_id
          }
          if (severUserInfo.company_grade === '5') {
            data.forEach(item => {
              if (item.id === severUserInfo.parent_ids.split(',')[3]) {
                this.areaMapInfo = item
              }
            })
            // severUserInfo.parent_ids.split(',')[3]
          }
        } else {
          this.$Notice.error({ title: '查询失败', desc: ret.data.errmsg })
        }
      })
    }
  },
  beforeDestroy () {
    this.map && this.map.destroy()
  },
  watch: {
    polygonMapModal (val) {
      if (!val) {
        this.inputSearch = ''
        this.dataList = []
        this.addressResult = ''
        this.map && this.map.destroy()
      }
    }
  }
}
</script>

  <style scoped>
  #mapPolygonForResidential {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
  }
  #leafletMap {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
  }
  .cardStrleClass{
    width:420px;
    position: absolute;
    z-index: 2022;
    top: 25px;
    left: 25px
  }
  .check-map{
    color: cornflowerblue;
    cursor: pointer;

  }
  /deep/ .leaflet-top{
    top: 85%;
  }
  </style>
